package de.revdev.streckenliste.dao;

import de.revdev.streckenliste.entities.Wildtyp;
import de.revdev.streckenliste.entities.Wildtyp_;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;

/**
 *
 * @author f.lindermaier
 */
@Stateless
@LocalBean
public class WildtypDAO extends AbstractDAO<Wildtyp> {

    @PersistenceContext(unitName = "Streckenliste-ejbPU")
    private EntityManager em;

    public WildtypDAO() {
        super(Wildtyp.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public List<Wildtyp> findWtAbschpfl() {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Wildtyp> cq = cb.createQuery(Wildtyp.class);
        Root<Wildtyp> c = cq.from(Wildtyp.class);
        cq.select(c);
        ParameterExpression<Boolean> p = cb.parameter(Boolean.class);
        cq.where(cb.equal(c.get("abschPlPfl"), p));
        TypedQuery tq = getEntityManager().createQuery(cq);
        return (List<Wildtyp>) tq.setParameter(p, true).getResultList();
    }

    public List<Wildtyp> findWtSortiert() {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Wildtyp> cq = cb.createQuery(Wildtyp.class);
        Root<Wildtyp> c = cq.from(Wildtyp.class);
        cq.select(c);
        cq.orderBy(cb.asc(c.get(Wildtyp_.nameWT)));
        TypedQuery tq = getEntityManager().createQuery(cq);
        return (List<Wildtyp>) tq.getResultList();
    }

    public Wildtyp findByName(String name) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Wildtyp> cq = cb.createQuery(Wildtyp.class);
        Root<Wildtyp> c = cq.from(Wildtyp.class);
        cq.select(c);
        ParameterExpression<String> p = cb.parameter(String.class);
        cq.where(cb.equal(c.get("nameWT"), p));
        TypedQuery tq = getEntityManager().createQuery(cq);
        return (Wildtyp) tq.setParameter(p, name).getSingleResult();
    }
}
